package fourfaith.com.ff_sl21_app;

import android.app.DatePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import org.apache.commons.lang.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import fourfaith.com.ff_sl21_app.adapter.PictureDetailAdapter;
import fourfaith.com.ff_sl21_app.utils.Constants;
import fourfaith.com.ff_sl21_app.utils.DatePickerDialogUtil;
import fourfaith.com.ff_sl21_app.utils.JsonRequest;
import fourfaith.com.ff_sl21_app.utils.RequestQueueSingleton;
import fourfaith.com.ff_sl21_app.utils.ResponseResult;
import fourfaith.com.ff_sl21_app.utils.SpaceItemDecoration;

public class PictureDetailActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener{

    private String siteCode,stnm;
    private Integer dsfl;

    private static Context context;
    private ImageView siteState;
    private TextView siteName;
    private ImageView back,query;

    private RecyclerView recyclerView;
    private LinearLayoutManager mLayoutManager;
    private static LinearLayout load_layout;
    private static SwipeRefreshLayout swipeRefreshLayout;
    private static List<Map<String, Object>> data = new ArrayList<>();
    private LinearLayout progressBar, listLayout, dataError,dataEmpty;
    private static PictureDetailAdapter pictureDetailAdapter;

    /** 分页信息 */
    private static int pageStart = 0;
    private static int pageSize = 15;

    /** 日期控件相关 */
    private DrawerLayout drawerLayout;
    private EditText beginTime;
    private EditText endTime;
    private DatePickerDialog dialog;
    private LinearLayout cancle, complete, cleanTime;
    private int year, monthOfYear, dayOfMonth;
    private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        context = this;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picture_detail);

        stnm = getIntent().getStringExtra("siteName");
        siteCode = getIntent().getStringExtra("siteCode");
        dsfl = getIntent().getIntExtra("siteState",0);

        initViews();
        initQuery();
        siteName.setText(stnm);
        siteState.setImageResource((Integer)dsfl);

        swipeRefreshLayout.setRefreshing(true);
        getDataRequest();
    }


    private void initViews() {
        cleanData();
        back = (ImageView) findViewById(R.id.back);
        query = (ImageView) findViewById(R.id.query);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        siteState = (ImageView) findViewById(R.id.siteState);
        siteName = (TextView) findViewById(R.id.siteName);

        progressBar = (LinearLayout) findViewById(R.id.progressBar);
        listLayout = (LinearLayout) findViewById(R.id.listLayout);
        dataError = (LinearLayout) findViewById(R.id.dataError);
        dataEmpty = (LinearLayout) findViewById(R.id.dataEmpty);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

        pictureDetailAdapter = new PictureDetailAdapter(this, data,recyclerView);
        // RecyclerView的ListView模式
        recyclerView.addItemDecoration(new SpaceItemDecoration(pictureDetailAdapter,10));
        // 设置RecyclerView属性为ListView
        mLayoutManager = new GridLayoutManager(context,2);

        // 设置RecyclerView属性为ListView
        recyclerView.setLayoutManager(mLayoutManager);
        // 加载适配器
        recyclerView.setAdapter(pictureDetailAdapter);
        // 添加滑动监听
        recyclerView.addOnScrollListener(mOnScrollListener);

        //下拉刷新
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);

        // 设置刷新时动画的颜色，可以设置4个
        swipeRefreshLayout.setColorSchemeResources(R.color.blue);

        swipeRefreshLayout.setOnRefreshListener(this);

        drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    }

    public void initQuery(){

        query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.openDrawer(GravityCompat.END);
            }
        });
        cancle = (LinearLayout)findViewById(R.id.cancle);
        complete = (LinearLayout)findViewById(R.id.finish);
        beginTime = (EditText)findViewById(R.id.beginTime);
        endTime = (EditText)findViewById(R.id.endTime);
        beginTime.setInputType(InputType.TYPE_NULL);
        endTime.setInputType(InputType.TYPE_NULL);
        cleanTime = (LinearLayout)findViewById(R.id.cleanTime);

        cancle.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                drawerLayout.closeDrawer(Gravity.END);
            }
        });

        cleanTime.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                beginTime.setText("");
                endTime.setText("");
            }
        });

        complete.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                String beginT = beginTime.getText().toString();
                String endT = endTime.getText().toString();

                if(StringUtils.isNotBlank(beginT) || StringUtils.isNotBlank(endT)){

                    if(StringUtils.isBlank(beginT)){
                        new AlertDialog.Builder(context)
                                .setIcon(android.R.drawable.ic_dialog_alert)
                                .setTitle("提示信息")
                                .setMessage("请输入开始时间!").show();

                        return;
                    }
                    if(StringUtils.isBlank(endT)){

                        new AlertDialog.Builder(context)
                                .setIcon(android.R.drawable.ic_dialog_alert)
                                .setTitle("提示信息")
                                .setMessage("请输入结束时间!").show();

                        return;
                    }

                }

                drawerLayout.closeDrawer(Gravity.END);
                cleanData();
                showLoadingPage();
                getDataRequest();
            }
        });

        //开始时间的监听事件
        beginTime.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                initDate(beginTime);
                dialog = DatePickerDialogUtil.initDialog(PictureDetailActivity.this, year, monthOfYear, dayOfMonth, beginTime);
                dialog.show();
            }

        });
        //结束时间的监听事件
        endTime.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                initDate(endTime);
                dialog = DatePickerDialogUtil.initDialog(PictureDetailActivity.this, year, monthOfYear, dayOfMonth, endTime);
                dialog.show();
            }
        });

    }

    /**
     * 日期初始化
     */
    private void initDate() {

        //日期初始化
        final Calendar cal = Calendar.getInstance();
        year = cal.get(Calendar.YEAR);
        monthOfYear = cal.get(Calendar.MONTH)+1;
        dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);

        // 设置初始值
        beginTime.setText(year + "-" + monthOfYear + "-" + dayOfMonth);
        endTime.setText(year + "-" + monthOfYear + "-" + dayOfMonth);

    }

    /**
     * 初始化日期
     *
     * @param textView
     */
    private void initDate(EditText textView) {
        String dateStr = textView.getText().toString();
        Calendar cal = Calendar.getInstance();
        try {
            if (dateStr != null && !dateStr.equals("")) {
                cal.setTime(df.parse(dateStr));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        year = cal.get(Calendar.YEAR);
        monthOfYear = cal.get(Calendar.MONTH);
        dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);

    }

    /**
     * 数据加载失败显示错误页面
     */
    public void showErrorPage() {
        progressBar.setVisibility(View.GONE);
        listLayout.setVisibility(View.GONE);
        dataError.setVisibility(View.VISIBLE);
        dataEmpty.setVisibility(View.GONE);
    }

    /**
     * 数据加载中页面
     */
    public void showLoadingPage() {

        progressBar.setVisibility(View.VISIBLE);
        dataError.setVisibility(View.GONE);
        dataEmpty.setVisibility(View.GONE);
        listLayout.setVisibility(View.GONE);
    }

    /**
     * 数据页面
     */
    public void showDataPage() {

        progressBar.setVisibility(View.GONE);
        dataError.setVisibility(View.GONE);
        listLayout.setVisibility(View.VISIBLE);
        dataEmpty.setVisibility(View.GONE);
    }

    /**
     * 空数据页面
     */
    public void showEmptyPage() {

        progressBar.setVisibility(View.GONE);
        dataError.setVisibility(View.GONE);
        listLayout.setVisibility(View.GONE);
        dataEmpty.setVisibility(View.VISIBLE);
    }

    /**
     * 接口获取数据
     * @return
     */
    private void getDataRequest() {

        String userId = Constants.getUserId();

        String url = null;
        String beginT = beginTime.getText().toString();
        String endT = endTime.getText().toString();
        try {
            url = Constants.devicePhotoList +"?userId=" + userId + "&stcd=" + siteCode + "&start="+pageStart + "&limit=" + pageSize
            +"&beginTime=" + beginT + "&endTime="+endT;

        } catch (Exception e) {
            e.printStackTrace();
        }

        RequestQueue mQueue = RequestQueueSingleton.getInstance(context).getRequestQueue();
        JsonRequest<ResponseResult> jsonRequest = new JsonRequest<>(Request.Method.GET, url, ResponseResult.class,
                new Response.Listener<ResponseResult>() {
                    @Override
                    public void onResponse(ResponseResult responseResult) {

                        JSONArray dataArray = (JSONArray) responseResult.getData();
                        Map<String, Object> map;

                        if (dataArray != null && dataArray.size() > 0) {
                            for (int i = 0; i < dataArray.size(); i++) {

                                pageStart++;

                                JSONObject model = dataArray.getJSONObject(i);
                                map = new HashMap<>();

                                map.put("deviceStatus","1".equals(String.valueOf(model.get("dsfl")))?R.mipmap.online:R.mipmap.offline);
                                map.put("deviceName",stnm);
                                map.put("deviceCode",model.get("stcd"));
                                map.put("photoUrl",Constants.HOST+model.get("photourl"));
                                map.put("photoTime",model.get("photoseetime"));

                                data.add(map);
                            }
                        }

                        pictureDetailAdapter.setData(data);
                        if(data==null || data.size()==0){
                            showEmptyPage();
                        }else{
                            showDataPage();
                        }
                        finishRefreshing();
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                finishRefreshing();
                showErrorPage();
                if (error.networkResponse == null) {
                    Toast.makeText(context, "连接超时，请求不到网络数据", Toast.LENGTH_SHORT).show();
                } else {
                    if (error.getMessage() == null) {
                        Toast.makeText(context, "接口服务器异常", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(context, error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }

            }

        });
        mQueue.add(jsonRequest);

    }

    // RecyclerView的滑动监听事件
    private RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener()
    {
        private int lastVisibleItem;

        // 滑动状态改变
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState)
        {
            super.onScrollStateChanged(recyclerView, newState);
            /**
             * scrollState有三种状态，分别是SCROLL_STATE_IDLE、SCROLL_STATE_TOUCH_SCROLL、SCROLL_STATE_FLING
             * SCROLL_STATE_IDLE是当屏幕停止滚动时
             * SCROLL_STATE_TOUCH_SCROLL是当用户在以触屏方式滚动屏幕并且手指仍然还在屏幕上时
             * SCROLL_STATE_FLING是当用户由于之前划动屏幕并抬起手指，屏幕产生惯性滑动时
             */
            if ( newState == RecyclerView.SCROLL_STATE_IDLE
                    && lastVisibleItem + 1 == pictureDetailAdapter.getItemCount()
                    && pictureDetailAdapter.isShowFooter())
            {

                load_layout = (LinearLayout) findViewById(R.id.load_layout);
                load_layout.setVisibility(View.VISIBLE);
                // 加载更多
                getDataRequest();
            }
        }

        // 滑动位置
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy)
        {
            super.onScrolled(recyclerView, dx, dy);
            // 给lastVisibleItem赋值
            // findLastVisibleItemPosition()是返回最后一个item的位置
            lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
        }
    };

    public static void finishRefreshing() {

        swipeRefreshLayout.setRefreshing(false);
        if(load_layout!=null) load_layout.setVisibility(View.GONE);
    }

    // 设置下拉刷新
    @Override
    public void onRefresh()
    {
        cleanData();
        pictureDetailAdapter.setData(data);
        getDataRequest();
    }

    public static void cleanData(){
        pageStart = 0;
        data.clear();
    }
}
